package com.mjk.manager.monitor.work;

import cn.hutool.core.util.RuntimeUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.core.redis.datatype.RedisHashUtils;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.BeanUtils;
import com.mjk.common.util.FileUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.manager.monitor.dto.MonitorDto;
import com.mjk.manager.monitor.model.EvnModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.EventObject;
import java.util.List;

/**
 * 环境接口类
 */
@BeeWork(work = "evn")
@ConditionalOnProperty(value = "bee.redis", havingValue = "true", matchIfMissing = false)
public class EvnWork extends BaseWork implements BeeApplicationListener {
    @Autowired
    private BeeDBService beeDBService;
    @Autowired
    private RedisTemplate redisTemplate;
    private final String EVN_KEY = "evn";
    /**
     * 获取环境信息
     * @param dto
     * @return
     */
    public BeeResponse getEvns(MonitorDto dto){
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new EvnModel());

        return BeeError.BEE_SUC.tranceError(beeDBService.findManyByWrapper(wrapper));
    }

    /**
     * 插入环境信息
     * @param model
     * @return
     */
    public BeeResponse saveEvn(EvnModel model){
        needParams(model, EvnModel::getEvnName);
        beeDBService.save(model);
        RedisHashUtils.set(redisTemplate,EVN_KEY,model.getEvnId()+"",model);
        return BeeError.BEE_SUC.tranceError();
    }
    /**
     * 修改环境信息
     * @param model
     * @return
     */
    public BeeResponse upEvn(EvnModel model){
        needParams(model, EvnModel::getEvnId);
        BeeQueryWrapper wrapper = new BeeQueryWrapper(model);
        wrapper.eq(EvnModel::getEvnId,model.getEvnId());
        beeDBService.update(wrapper);
        EvnModel tmp = (EvnModel)RedisHashUtils.get(redisTemplate,EVN_KEY,model.getEvnId()+"");
        if(ObjectUtils.isNotEmpty(model.getClientIp())){
            tmp.setClientIp(model.getClientIp());
        }
        if(ObjectUtils.isNotEmpty(model.getServerIp())){
            tmp.setServerIp(model.getServerIp());
        }
        RedisHashUtils.set(redisTemplate,EVN_KEY,model.getEvnId()+"",tmp);
        return BeeError.BEE_SUC.tranceError();
    }
    /**
     * 打开配置文件
     * @param model
     * @return
     */
    public BeeResponse openEvnConf(EvnModel model){
        needParams(model,EvnModel::getSoftLoadPath);
        String fileContent = FileUtils.readString(model.getSoftLoadPath()+"/conf/nginx.conf","utf-8");
        return BeeError.BEE_SUC.tranceError(fileContent);
    }

    /**
     * 更新配置
     * @param dto
     * @return
     */
    public BeeResponse updateEvnConf(MonitorDto dto){
        needParams(dto,MonitorDto::getSoftLoadPath,MonitorDto::getConfContent);
        FileUtils.write2File(dto.getSoftLoadPath()+"/conf/nginx.conf",dto.getConfContent());
        return BeeError.BEE_SUC.tranceError();
    }

    /**
     * 执行命令行 并返回调用结果
     * @param dto
     * @return
     */
//    public BeeResponse exec(MonitorDto dto) throws IOException {
//        needParams(dto,MonitorDto::getExecStr);
//        String checkCmd = "tasklist /fi \"imagename eq nginx.exe\"";
//        Process checkProcess = Runtime.getRuntime().exec(checkCmd);
//        String result = RuntimeUtil.getResult(checkProcess);
//        String cmd = "";
//        if(result.contains("没有运行的任务")){
//            cmd = "cmd /c " + dto.getSoftLoadPath().replace(" ", "\" \"") +
//                    " nginx.exe";
//        }else{
//            cmd = "cmd /c " + dto.getSoftLoadPath().replace(" ", "\" \"") +
//                    dto.getExecStr();
//        }
//        Process process = Runtime.getRuntime().exec(cmd);
//        return BeeError.BEE_SUC.tranceError(RuntimeUtil.getResult(process));
//    }

    @Override
    public void doApplicationEvent(ContextRefreshedEvent event) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new EvnModel());
        List<EvnModel> evns = beeDBService.findManyByWrapper(wrapper);
        if(!CollectionUtils.isEmpty(evns)){
            for (EvnModel evn : evns) {
                RedisHashUtils.set(redisTemplate,EVN_KEY,evn.getEvnId()+"",evn);
            }
        }
    }
}
